package com.wuyou.securitydemo.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.wuyou.sso.common.contant.AuthConstants;
import com.wuyou.sso.common.bean.ResultBean;
import com.wuyou.securitydemo.config.IgnoreChecker;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.http.MediaType;
import org.springframework.security.core.SpringSecurityMessageSource;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Authorization过滤器
 *
 * @Date 2025/4/16 11:15
 * @Author 无忧
 */
public class AuthorizationFilter extends IgnoreChecker implements Filter {

    private final MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //处理匿名接口
        if (this.isIngores(req)) {
            chain.doFilter(request, response);
            return;
        }
        String token = ServletUtil.getHeader(req, AuthConstants.TOKEN_HEADER_PARAM, "");
        if (StrUtil.isBlank(token) || !token.trim().startsWith(AuthConstants.BEARER_TYPE)) {
            response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
            ServletUtil.write((HttpServletResponse) response, JSONUtil.toJsonStr(ResultBean.failed("用户凭证已过期")), MediaType.APPLICATION_JSON_VALUE);
        } else {
            chain.doFilter(request, response);
        }
    }
}
